#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import re
import json
import logging
import os
from utils import utils_data, ErrorInfoBuilder

logger = logging.getLogger('my_logger')


def check_syscap():
    pattern = re.compile(r'(\bohos_[a-z_]+_suite)\("([^"]+)"\)\s*\{')
    file_entities = utils_data.get_file()

    has_error = False
    hvigor_templates = ['ohos_js_app_suite', 'ohos_app_assist_suite']
    no_hvigor_templates = ['ohos_hap_assist_suite', 'ohos_js_hap_suite']

    for file_entity in file_entities:
        if file_entity.file_name == 'BUILD.gn':
            file_path = file_entity.full_path

            with open(file_path, 'r') as file:
                lines = file.readlines()

                for line_num, line in enumerate(lines, start=1):
                    match = pattern.search(line)
                    if match:
                        template = match.group(1).strip()
                        if template in no_hvigor_templates:
                            continue
                        elif template in hvigor_templates:
                            dir_path = os.path.dirname(file_path)
                            main_dir = os.path.join(dir_path, 'entry/src/main')
                            ohosTest_dir = os.path.join(dir_path, 'entry/src/ohosTest')
                            main_dir_exists = os.path.exists(main_dir)
                            ohosTest_dir_exists = os.path.exists(ohosTest_dir)
                            main_has_syscap = False
                            ohosTest_has_syscap = False
                            if main_dir_exists:
                                main_has_syscap = os.path.exists(os.path.join(main_dir, 'syscap.json'))
                            if ohosTest_dir_exists:
                                ohosTest_has_syscap = os.path.exists(os.path.join(ohosTest_dir, 'syscap.json'))
                            if (main_dir_exists and ohosTest_dir_exists and main_has_syscap and ohosTest_has_syscap) or (
                                    main_has_syscap and not ohosTest_dir_exists):
                                if main_has_syscap:
                                    main_syscap_path = os.path.join(main_dir, 'syscap.json')
                                    if not check_syscap_content(main_syscap_path):
                                        parent_dir = os.path.basename(os.path.dirname(file_path))
                                        buggy_code_message = f"{parent_dir}工程的entry/src/main目录下的syscap.json配置不符合要求，应用的deviceTypes必须清空，syscap必须配置正确"
                                        error_info = ErrorInfoBuilder() \
                                            .set_buggy_file_path(file_entity.file_path) \
                                            .set_defect_type("XTS.CHECK.SYSCAP.01") \
                                            .set_description("hvigor工程syscap.json配置不符合要求") \
                                            .set_main_buggy_line(0) \
                                            .set_main_buggy_code(buggy_code_message) \
                                            .build()
                                        utils_data.write_error_to_json_file(error_info)
                                        logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                                        has_error = True

                                if ohosTest_has_syscap:
                                    ohosTest_syscap_path = os.path.join(ohosTest_dir, 'syscap.json')

                                    if not check_syscap_content(ohosTest_syscap_path):
                                        parent_dir = os.path.basename(os.path.dirname(file_path))
                                        buggy_code_message = f"{parent_dir}工程的entry/src/ohosTest目录下的syscap.json配置不符合要求，应用的deviceTypes必须清空，syscap必须配置正确"
                                        error_info = ErrorInfoBuilder() \
                                            .set_buggy_file_path(file_entity.file_path) \
                                            .set_defect_type("XTS.CHECK.SYSCAP.01") \
                                            .set_description("hvigor工程syscap.json配置不符合要求") \
                                            .set_main_buggy_line(0) \
                                            .set_main_buggy_code(buggy_code_message) \
                                            .build()
                                        utils_data.write_error_to_json_file(error_info)
                                        logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                                        has_error = True
                            else:
                                parent_dir = os.path.basename(os.path.dirname(file_path))
                                if not main_has_syscap and not ohosTest_dir_exists:
                                    buggy_code_message = f"{parent_dir}工程的entry/src/main目录缺少syscap.json 文件"
                                elif not ohosTest_has_syscap and main_has_syscap:
                                    buggy_code_message = f"{parent_dir}工程的 entry/src/ohosTest目录缺少syscap.json文件"
                                else:
                                    buggy_code_message = f"{parent_dir}工程缺少对应的syscap.json文件"
                                error_info = ErrorInfoBuilder() \
                                    .set_buggy_file_path(file_entity.file_path) \
                                    .set_defect_type("XTS.CHECK.SYSCAP.01") \
                                    .set_description("hvigor工程必须配置syscap.json") \
                                    .set_main_buggy_line(0) \
                                    .set_main_buggy_code(buggy_code_message) \
                                    .build()

                                utils_data.write_error_to_json_file(error_info)
                                logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                                has_error = True

    if has_error:
        logger.info("syscap.json检查完成，错误信息已写入xts_result.json")
    else:
        logger.info("syscap.json检查通过")


def check_syscap_content(syscap_path):
    try:
        with open(syscap_path, 'r') as f:
            data = json.load(f)
            general = data.get('devices', {}).get('general', [])
            custom = data.get('devices', {}).get('custom', [])
            xts = []
            for item in custom:
                xts.extend(item.get('xts', []))
            return len(general) == 0 and len(xts) > 0
    except Exception as e:
        logger.error(f"读取 {syscap_path} 时出错: {e}")
        return False